package bookStore.service.privilege;

import java.sql.SQLException;
import java.util.List;

import bookStore.dao.privilege.ResourceDao;
import bookStore.dao.privilege.ResourceDaoImpl;
import bookStore.dao.privilege.RoleDao;
import bookStore.dao.privilege.RoleDaoImpl;
import bookStore.dao.privilege.UserDao;
import bookStore.dao.privilege.UserDaoImpl;
import bookStore.po.User;
import bookStore.service.ServiceTemplate;
import bookStore.vo.UserWithResources;

public class UserServiceImpl extends ServiceTemplate implements UserService {

	private UserDao dao;
	private RoleDao roleDao;
	private ResourceDao resourceDao;

	public UserServiceImpl() {
		dao = new UserDaoImpl(this.connection);
		roleDao = new RoleDaoImpl(this.connection);
		resourceDao = new ResourceDaoImpl(this.connection);
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<User> queryAll(int offset, int pageSize) {
		// TODO Auto-generated method stub
		return dao.queryAll(offset, pageSize);
	}

	@Override
	public void save(User t) {
		dao.save(t);
	}

	@Override
	public User get(int id) {
		
		return dao.get(id);
	}

	@Override
	public long count() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void update(User t) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(int id) {

	}

	@Override
	public User login(String username, String password) {
		return dao.login(username, password);
	}

	@Override
	public List<String> getBlackList(int userId) {
		return resourceDao.getBlackListForUser(userId);
	}

	@Override
	public int register(User u)  {
		try {
			this.connection.setAutoCommit(false);
			dao.register(u);
			int userId = (int)dao.getInsertedId();
			roleDao.addRoleForUser(userId, new int[] {2});
			this.connection.commit();
			return userId;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				this.connection.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return -1;
		}
		
	}

	@Override
	public void updateUserWithRole(User u,int [] roleIds) {
		try {
			this.connection.setAutoCommit(false);
			dao.update(u);
			int userId = u.getId();
			roleDao.deleteRoleForUser(userId);
			if(roleIds!=null) {
				roleDao.addRoleForUser(userId, roleIds);
			}
			this.connection.commit();
			
		} catch (SQLException e) {
			try {
				this.connection.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		
	}




}
